package com.controller;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.base.BaseController;
import com.common.MsgReturn;
import com.model.User;
import com.service.ModuleService;
import com.service.UserService;
import com.util.JSONUtil;
import com.util.SessionUtils;
import com.util.URLUtils;
import com.util.WebConstants;

@Controller
public class LoginController extends BaseController {

	
	@Resource
	private UserService userService;
	@Resource
	private ModuleService moduleService;//这个是报错的吗？

	@RequestMapping("/login")
	public void  login(User user,String authCode,HttpServletRequest request,HttpServletResponse response) throws Exception{
		String vcode  = SessionUtils.getValidateCode(request);
        if(null!=vcode&&!"".equals(vcode))
        {
            //清除验证码，确保验证码只能用一次
            SessionUtils.removeValidateCode(request);
            if(StringUtils.isBlank(authCode)){
                writerJson(response, errorMsg("验证码不能为空"));
            }
            //判断验证码是否正确
            if(!(vcode.toLowerCase()).equals(authCode)&&!authCode.equals(vcode)){
                writerJson(response, errorMsg("验证码输入错误"));
            }
        }else {
            writerJson(response, errorMsg("验证码已失效，请刷新验证码"));
        }
	    user=userService.login(user);
	    if(null!=user&&user.getId()>0)
	    {//登录成功
	    	writerJson(response, successMsg(user.getAccount()+"登录成功"));
	    	request.getSession().setAttribute(WebConstants.CURRENT_USER, user); 
	    }else
	    {//登录失败
	    	writerJson(response, JSONUtil.toJson(new MsgReturn(false,"登录失败！用户名或密码输入错误！")));
	    }

		
	   
	}
	@RequestMapping(value="/main")
	public ModelAndView login(ModelMap model) {
		    Map<String,Object>  context = new HashMap<String, Object>();
			return forword("main",context);
	}
	
	/**
	 * 退出登录
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/logout")
	public void  logout(HttpServletRequest request,HttpServletResponse response) throws Exception{

		response.sendRedirect(URLUtils.get("msUrl")+"/login.shtml");
	}
	

}
